<template>
  <div class="my-requests">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>我的申请</span>
        </div>
      </template>

      <el-table :data="requests" v-loading="loading">
        <el-table-column prop="processInstanceId" label="流程实例ID" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button 
                type="primary" 
                size="small"
                style="margin-right: 8px"
                @click="handleView(row)"
              >
                查看详情
              </el-button>
              <el-button 
                type="info" 
                size="small"
                @click="handleViewHistory(row)"
              >
                审批历史
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="申请详情"
      width="800px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="流程名称">{{ currentRequest?.processName }}</el-descriptions-item>
        <el-descriptions-item label="流程实例ID">{{ currentRequest?.processInstanceId }}</el-descriptions-item>
        <el-descriptions-item label="发起人">{{ currentRequest?.requesterName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentRequest?.status)">
            {{ getStatusText(currentRequest?.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(currentRequest?.createdAt) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 表单内容 -->
      <div class="form-content">
        <div class="form-title">表单内容</div>
        <el-descriptions :column="1" border>
          <el-descriptions-item 
            v-for="(value, key) in currentRequest?.formData" 
            :key="key"
            :label="getFieldLabel(key)"
          >
            {{ formatFieldValue(key, value) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 审批历史对话框 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="审批历史"
      width="700px"
    >
      <el-timeline>
        <!-- 流程发起事件 -->
        <el-timeline-item
          type="primary"
          :timestamp="formatDateTime(currentRequest?.createdAt)"
        >
          <h4>流程发起</h4>
          <p>发起人：{{ currentRequest?.requesterName }}</p>
        </el-timeline-item>
        
        <el-timeline-item
          v-for="item in approvalHistory"
          :key="item.id"
          :type="item.approved ? 'success' : 'danger'"
          :timestamp="formatDateTime(item.createdAt)"
        >
          <h4>{{ item.taskName }}</h4>
          <p>审批人：{{ item.approverName }}</p>
          <p>结果：{{ item.approved ? '同意' : '拒绝' }}</p>
          <p v-if="item.comment">意见：{{ item.comment }}</p>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const requests = ref([])
const detailDialogVisible = ref(false)
const historyDialogVisible = ref(false)
const currentRequest = ref(null)
const approvalHistory = ref([])

const loadRequests = async () => {
  loading.value = true
  try {
    const response = await request.get('/process/my-requests')
    requests.value = response.data
  } catch (error) {
    console.error('加载申请列表失败:', error)
    ElMessage.error('加载申请列表失败')
  } finally {
    loading.value = false
  }
}

const getStatusType = (status) => {
  const statusMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'COMPLETED': 'success'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '处理中',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'COMPLETED': '已完成'
  }
  return statusMap[status] || status
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}

const handleView = async (row) => {
  try {
    // 获取流程详情，包括表单数据
    const response = await request.get(`/process/process-instances/${row.processInstanceId}`)
    currentRequest.value = {
      ...row,
      ...response.data
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('加载详情失败:', error)
    ElMessage.error('加载详情失败')
  }
}

const handleViewHistory = async (row) => {
  try {
    const response = await request.get(`/process/process-instances/${row.processInstanceId}/history`)
    approvalHistory.value = response.data
    currentRequest.value = {
      ...row
    }
    historyDialogVisible.value = true
  } catch (error) {
    console.error('加载审批历史失败:', error)
    ElMessage.error('加载审批历史失败')
  }
}

// 获取字段标签
const getFieldLabel = (fieldId) => {
  // 这里可以根据实际情况从表单配置中获取字段标签
  const fieldLabels = {
    title: '标题',
    content: '内容',
    amount: '金额',
    // ... 其他字段
  }
  return fieldLabels[fieldId] || fieldId
}

// 格式化字段值
const formatFieldValue = (fieldId, value) => {
  if (value === null || value === undefined) return '-'
  
  // 根据字段类型格式化值
  switch (fieldId) {
    case 'amount':
      return `¥ ${value.toFixed(2)}`
    case 'date':
      return formatDateTime(value)
    default:
      return value
  }
}

onMounted(() => {
  loadRequests()
})
</script>

<style scoped>
.my-requests {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-descriptions__label) {
  width: 120px;
  justify-content: right;
}

.el-timeline {
  margin: 20px;
}

.el-timeline h4 {
  margin: 0;
  font-size: 14px;
  color: #303133;
}

.el-timeline p {
  margin: 5px 0;
  font-size: 13px;
  color: #606266;
}

.form-content {
  margin-top: 20px;
}

.form-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 4px solid #409eff;
}

:deep(.el-descriptions__label) {
  width: 120px;
  justify-content: right;
  background-color: #fafafa;
}

:deep(.el-descriptions__content) {
  padding: 12px 16px;
}
</style> 